const path = require("path");

const Multer = require("@koa/multer");
const Jimp = require("jimp");
const { AVATAR_PATH, PICTURE_PATH } = require("../constants/file-path");

// 头像上传
const avatarUpload = Multer({
	// dest: AVATAR_PATH
	storage: Multer.diskStorage({
		// 存储路径
		destination: (req, file, cb) => {
			cb(null, AVATAR_PATH);
		},
		// 文件名
		filename: (req, file, cb) => {
			cb(null, Date.now() + "_" + file.originalname);
		}
	})
});
const avatarHandler = avatarUpload.single("avatar");

// 上传内容配图
const pictureUpload = Multer({
	// dest: PICTURE_PATH
	storage: Multer.diskStorage({
		// 存储路径
		destination: (req, file, cb) => {
			cb(null, PICTURE_PATH);
		},
		// 文件名
		filename: (req, file, cb) => {
			cb(null, Date.now() + "_" + file.originalname);
		}
	})
});
const pictureHandler = pictureUpload.array("picture", 9); //最多9张图

// 处理图像尺寸
const pictureResize = async (ctx, next) => {
	// 获取所有图像信息
	const files = ctx.request.files;

	//   对图像进行处理 (sharp/jimp)
	for (let file of files) {
		const destPath = path.join(
			file.destination,
			file.filename.split(".")[0]
		);
		Jimp.read(file.path).then((image) => {
			image
				.resize(1280, Jimp.AUTO)
				.write(`${destPath}-large.${file.mimetype.split("/")[1]}`);
			image
				.resize(640, Jimp.AUTO)
				.write(`${destPath}-middle.${file.mimetype.split("/")[1]}`);
			image
				.resize(320, Jimp.AUTO)
				.write(`${destPath}-small.${file.mimetype.split("/")[1]}`);
		});
	}

	await next();
};

module.exports = {
	avatarHandler,
	pictureHandler,
	pictureResize
};
